import router from "@/router";
import { useUserStore } from "@/stores/user";
import pinia from "@/stores";
import type {
  RouteRecordName,
} from "vue-router";
const store = useUserStore(pinia);

const blackList: RouteRecordName[] = ["/CreateTieba"];

router.beforeEach(async(to, from, next) => {
  //是否拥有token
  if (store.token) {
    if(to.path=="/login"){
        next("/")
    }
    //是否有用户信息
    if(store.userInfo._id){
        next();
    }
    else
    {
       try {
        await store.getUserInfo()
        next()
       } catch (e) {
        //token过期
        store.reset()
        next(`/login?target=${to.path}`)
       }
    }
    
  } 
  else 
  {
    //需要登录访问的页面
    if (blackList.includes(to.path as RouteRecordName)) {
      next(`/login?target=${to.path}`);
    } 
    else 
    {
      next();
    }
  }
});
